<template>
  <div>
    <!-- 授权钥匙选择对话框 -->
<!--    <el-dialog :title="'授权钥匙'" :visible.sync="isShow" width="400px" append-to-body>
      <img src="@/assets/images/lxkp_bg_new.897e2d12.png" width="350px" style="margin: 5px; cursor: pointer;"
        @click="clickCard" /> -->
  <!--    <img src="@/assets/images/offline_password_img_new.56a6ed28.png" width="350px"
        style="margin: 5px; cursor: pointer;" @click="clickCustom" /> -->
    <!-- </el-dialog> -->

    <!-- 授权钥匙对话框 -->
    <el-dialog :title="title" :visible.sync="showCustom" v-if="showCustom" width="900px" append-to-body
      :show-close="false">
      <!-- 房间信息显示区域 -->
      <div v-if="tenantInfo.roomInfo || tenantInfo.selectedRooms" class="room-info-section" style="margin-bottom: 20px; padding: 15px; background: #f5f7fa; border-radius: 8px;">
        <!-- <h4 style="margin: 0 0 10px 0; color: #303133;">房间信息</h4> -->
        <div v-if="tenantInfo.isBatch" class="batch-rooms">
          <p style="margin: 0 0 8px 0; color: #606266;">
            <i class="el-icon-info" style="color: #409eff; margin-right: 5px;"></i>
            已选择 <span style="color: #409eff; font-weight: bold;">{{ tenantInfo.batchCount }}</span> 个房间，将一次性为所有房间办理钥匙
          </p>
          <div class="room-list" style="max-height: 120px; overflow-y: auto;">
            <div v-for="(room, index) in tenantInfo.selectedRooms" :key="index"
                 style="padding: 8px; margin: 4px 0; background: white; border-radius: 4px; border-left: 3px solid #409eff;">
              <span style="font-weight: 500; color: #303133;">
                {{ room.cellName || '-' }} / {{ room.unitName || '-' }} / {{ room.floorName || '-' }} / {{ room.roomName }}
              </span>
            </div>
          </div>
        </div>
        <div v-else class="single-room">
          <div style="padding: 8px; background: white; border-radius: 4px; border-left: 3px solid #67c23a;">
            <span style="font-weight: 500; color: #303133;">
              为房间：{{ tenantInfo.roomInfo.cellName || '-' }} / {{ tenantInfo.roomInfo.unitName || '-' }} / {{ tenantInfo.roomInfo.floorName || '-' }} / {{ tenantInfo.roomInfo.roomName }} 办理钥匙
            </span>
          </div>
        </div>
      </div>

      <el-form ref="keyForm" :model="keyForm" :rules="rulesNEW" label-width="80px">
        <!-- 基本信息区域 -->
        <div style="margin-bottom: 20px;">
          <!-- <h4 style="margin-bottom: 15px;">基本信息</h4> -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="userName" label-width="80px" style="width: 320px;">
                <el-input v-model="keyForm.userName" placeholder="请输入住户名" :disabled="keyForm.relation === '0'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话" prop="userPhone" label-width="80px" style="width: 320px;">
                <el-input v-model="keyForm.userPhone" placeholder="请输入住户电话" :disabled="keyForm.relation === '0'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
       <!--     <el-col :span="12">
              <el-form-item label="类别" prop="relation" label-width="80px" style="width: 320px;">
                <el-select v-model="keyForm.relation" placeholder="请选择" :disabled="keyForm.relation === '0'" @change="handleRelationChange">
                  <el-option
                    v-for="dict in dict.type.relation"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <div style="float: left;">
                <el-form-item label="密码" prop="password" label-width="80px" style="width: 320px;" v-if="radioType == '1'">
                  <el-input
                    type="number"
                    v-model="keyForm.password"
                    placeholder="请输入6位数密码（不能以0开头）"
                    minlength="6"
                    maxlength="6"
                    :key="'password-input-' + radioType"
                  />
                  <div class="input-hint">密码必须是6位数字，且首位不能为0，不能使用连续数字（如123456或654321）</div>
                </el-form-item>

                <el-form-item label="卡片" prop="password" label-width="80px" style="width: 320px;" v-if="radioType == '2'">
                  <el-input type="text" v-model="keyForm.password" :disabled="keyForm.relation === '0'" placeholder="请输入卡号" maxlength="20" />
                </el-form-item>
              </div>
            </el-col>

          </el-row>

        </div>


        <div style="margin: -3px 0px -26px 3px;">
          <p>已授权密码：（添加成功后第一次使用该密码<span style="color: red;">按9#后</span>密码生效或等待24小时之后自动生效）</p>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitFormRuzhu">确 定</el-button>
        <el-button @click="cancelKey">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 办理钥匙进度对话框 -->
    <el-dialog title="办理钥匙进度" :visible.sync="keyAuthProgressVisible" width="600px" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="keyAuthProgress.status !== 'processing'">
      <div class="key-auth-progress-content">
        <!-- 用户信息 -->
        <div class="user-info">
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="用户姓名">{{ keyAuthProgressData.name }}</el-descriptions-item>
            <el-descriptions-item label="学工号">{{ keyAuthProgressData.idCardNumber }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 进度条 -->
        <div class="progress-section">
          <div class="progress-header">
            <span class="progress-title">办理钥匙进度</span>
            <span class="progress-text">{{ keyAuthProgress.current }}/{{ keyAuthProgress.total }}</span>
          </div>
          <el-progress
            :percentage="keyAuthProgress.total > 0 ? Math.round((keyAuthProgress.current / keyAuthProgress.total) * 100) : 0"
            :status="keyAuthProgress.status === 'error' ? 'exception' : keyAuthProgress.status === 'success' ? 'success' : ''"
            :stroke-width="8" />
          <div class="progress-status">
            <el-tag :type="getKeyAuthProgressStatusType()" size="small">
              {{ getKeyAuthProgressStatusText() }}
            </el-tag>
          </div>
        </div>

        <!-- 当前状态消息 -->
        <div class="status-message" v-if="keyAuthProgress.message">
          <i class="el-icon-info"></i>
          <span>{{ keyAuthProgress.message }}</span>
        </div>

        <!-- 详细进度列表 -->
        <div class="progress-details" v-if="keyAuthProgress.details.length > 0">
          <div class="details-header">
            <span>详细进度</span>
            <el-button
              type="primary"
              size="mini"
              @click="copyAllFailureInfo"
              style="float: right; margin-left: 10px;"
              title="复制所有失败信息">
              <i class="el-icon-document-copy"></i>
              一键复制失败信息
            </el-button>
          </div>
          <el-table :data="keyAuthProgress.details" size="small" border>
            <el-table-column label="校区" prop="cellName" width="100" />
            <el-table-column label="楼栋" prop="unitName" width="100" />
            <el-table-column label="楼层" prop="floorName" width="100" />
            <el-table-column label="房间" prop="roomName" width="120" />
            <el-table-column label="钥匙类型" prop="keyType" width="100" />
            <el-table-column label="状态" width="80">
              <template slot-scope="scope">
                <el-tag :type="getDetailStatusType(scope.row.status)" size="mini">
                  {{ getDetailStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="失败原因" prop="errorReason" min-width="200" />
            <el-table-column label="time" prop="time" width="120" />
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="keyAuthProgress.status === 'processing'" type="primary" disabled>
          处理中...
        </el-button>
        <el-button v-else-if="keyAuthProgress.status === 'success'" type="success"
          @click="keyAuthProgressVisible = false">
          完成
        </el-button>
        <el-button v-else-if="keyAuthProgress.status === 'error'" type="danger"
          @click="keyAuthProgressVisible = false">
          关闭
        </el-button>
        <el-button v-if="keyAuthProgress.status !== 'processing'" @click="keyAuthProgressVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    tenantToKey
  } from "@/api/lock/tenantUser";
  import {
    batchAddTenantkey
  } from "@/api/lock/tenantkey";

  // 定义一个独立的 formatDateTime 函数
  function formatDateTime(dateTimeStr) {
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    const hours = ('0' + date.getHours()).slice(-2);
    const minutes = ('0' + date.getMinutes()).slice(-2);
    const seconds = ('0' + date.getSeconds()).slice(-2);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  export default {
    name: "KeyAuth",
    dicts: ['relation'],
    data() {
      return {
        tenantInfo:{},
        // 是否显示授权钥匙选择对话框
        isShow: false,
        // 是否显示授权钥匙详情对话框
        showCustom: false,
        // 标题
        title: "",
        // 钥匙类型（1：密码，2：卡片）
        radioType: '1',
        // 是否显示刷卡区域
        showka: true,
        // 时间选择
        radio: null,
        // 钥匙表单
        keyForm: {},
        
        // 办理钥匙进度相关数据
        keyAuthProgressVisible: false,
        keyAuthProgressData: {},
        keyAuthWebSocket: null,
        keyAuthProgress: {
          current: 0,
          total: 0,
          status: 'processing', // processing, success, error
          message: '',
          details: []
        },
        
        // 表单校验规则
        rulesNEW: {
          startTime: [{
            required: true,
            message: '请选择开始时间',
            trigger: 'blur'
          }],
          endTime: [{
            required: true,
            message: '请选择结束时间',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请输入密码或卡号',
            trigger: 'blur'
          }],
          relation: [{
            required: true,
            message: '请选择关系',
            trigger: 'change'
          }],
          userName: [{
            required: true,
            message: '请输入住户名',
            trigger: 'blur'
          }],
          userPhone: [{
            required: true,
            message: '请输入住户电话',
            trigger: 'blur'
          }]
        }
      };
    },
    computed: {
      endPickerOptions() {
        return {
          disabledDate: time => {
            const startTime = new Date(this.keyForm.startTime).setHours(0, 0, 0, 0);
            const currentDate = new Date().setHours(0, 0, 0, 0);
            return time.getTime() < startTime - 86400000 || time.getTime() < currentDate;
          }
        };
      },
      defaultTime() {
        return '00:00:00';
      }
    },
    created() {
      // 不再需要手动获取关系字典数据
    },
    
    beforeDestroy() {
      // 组件销毁前关闭WebSocket连接
      if (this.keyAuthWebSocket) {
        this.keyAuthWebSocket.close();
        this.keyAuthWebSocket = null;
      }
    },
    methods: {
      // 关系变更处理
      handleRelationChange(value) {
        console.log("关系变更为:", value);
        console.log("当前人员信息:", this.tenantInfo);

        if (value === '0') {
          // 获取人员电话 - 检查可能的字段名
          const tenanuserPhone = this.tenantInfo.phone || this.tenantInfo.mobile || this.tenantInfo.phoneNumber || '';

          // 如果是本人，自动填充信息
          this.keyForm.userName = this.tenantInfo.name || '';
          this.keyForm.userPhone = tenanuserPhone;

          console.log("自动填充本人信息:", {
            name: this.keyForm.userName,
            phone: this.keyForm.userPhone
          });
        } else {
          // 如果不是本人，清空信息
          this.keyForm.userName = '';
          this.keyForm.userPhone = '';
        }
      },



      // 显示授权钥匙对话框
      showDialog(tenantInfo) {
        this.isShow = true;
        this.showCustom = true; // 显示表单对话框
        this.title = "授权钥匙";
        this.tenantInfo = tenantInfo;
        // 打印完整的tenant信息，检查属性
        console.log("钥匙数据(完整):", tenantInfo);

        // 重置密码和卡号值
        this.passwordValue = '';
        this.cardValue = '';

        // 设置默认时间
        this.setDefaultTimes();

        // 设置默认类型为密码授权
        this.radioType = tenantInfo.type || '2';  // 如果有类型则使用已有类型，否则默认为2（卡片）



        // 获取人员电话 - 检查可能的字段名
        const tenanuserPhone = tenantInfo.phone || tenantInfo.mobile || tenantInfo.phoneNumber || '';
        console.log("人员电话信息:", {
          phone: tenantInfo.phone,
          mobile: tenantInfo.mobile,
          phoneNumber: tenantInfo.phoneNumber,
          selected: tenanuserPhone
        });

        // 设置其他表单字段
        this.keyForm = {
          userId: tenantInfo.userId || tenantInfo.id,
          tenantId: tenantInfo.tenantId || tenantInfo.id,
          homeId: tenantInfo.homeId,
          cellId: tenantInfo.cellId,
          unitId: tenantInfo.unitId,
          floorId: tenantInfo.floorId,
          idCardNumber: tenantInfo.idCardNumber,
          remark: tenantInfo.remark || tenantInfo.name,
          password: tenantInfo.password || '',
          startTime: tenantInfo.startTime || this.keyForm.startTime,
          endTime: tenantInfo.endTime || this.keyForm.endTime,
          // 强制默认关系为本人
          relation: tenantInfo.relation || '0',
          // 自动填充本人信息
          userName: tenantInfo.userName || tenantInfo.name || '',
          userPhone: tenantInfo.userPhone || tenanuserPhone
        };

        // 如果默认为本人关系，确保填充住户本人信息
        if (this.keyForm.relation === '0') {
          this.keyForm.userName = tenantInfo.name || '';
          this.keyForm.userPhone = tenanuserPhone;
        }



        // 新增：如果类型为卡片且有cardNo，自动赋值卡号
        if ((tenantInfo.type === '2' || this.radioType === '2') && tenantInfo.cardNo) {
          this.keyForm.password = tenantInfo.cardNo;
          this.cardValue = tenantInfo.cardNo;
        }

        // 如果类型为卡片，自动设置用户的卡号
        if (this.radioType === '2') {
          this.keyForm.password = tenantInfo.cardNo || '';
          this.cardValue = tenantInfo.cardNo || '';
        }

        // 默认选中"1月"单选按钮
        this.radio = "1月";
      },

      // 卡片授权
      clickCard() {
        this.showCustom = true;
        // 在切换类型前，保存当前的值
        if (this.radioType === '1' && this.keyForm.password) {
          this.passwordValue = this.keyForm.password;
        }

        // 切换到卡片类型
        this.radioType = '2';  // '2' 表示卡片类型
        this.title = "离线卡片授权";

        // 设置默认时间
        this.setDefaultTimes();

        // 优先使用tenantInfo.cardNo自动带入卡号
        this.$nextTick(() => {
          if (this.tenantInfo && this.tenantInfo.cardNo) {
            this.keyForm.password = this.tenantInfo.cardNo;
            this.cardValue = this.tenantInfo.cardNo;
          } else {
            this.keyForm.password = this.cardValue;
          }
        });

        // 默认选中"1月"单选按钮
        this.radio = "1月";
      },

      // 密码授权
      clickCustom() {
        this.showCustom = true;

        // 在切换类型前，保存当前的值
        if (this.radioType === '2' && this.keyForm.password) {
          this.cardValue = this.keyForm.password;
        }

        // 切换到密码类型
        this.radioType = '1';  // '1' 表示密码类型
        this.title = "离线密码授权";

        // 设置默认时间
        this.setDefaultTimes();

        // 从缓存恢复密码值
        this.$nextTick(() => {
          this.keyForm.password = this.passwordValue;
        });

        // 默认选中"1月"单选按钮
        this.radio = "1月";
      },

      // 设置默认开始和结束时间
      setDefaultTimes() {
        // 设置开始时间为当前日期时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const currentDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

        // 设置默认结束时间为一个月后
        const endDate = new Date(now);
        endDate.setMonth(now.getMonth() + 1);
        const endYear = endDate.getFullYear();
        const endMonth = String(endDate.getMonth() + 1).padStart(2, '0');
        const endDay = String(endDate.getDate()).padStart(2, '0');
        const endDateTime = `${endYear}-${endMonth}-${endDay} ${hours}:${minutes}:${seconds}`;

        // 如果keyForm不存在，初始化它，但保留现有值
        if (!this.keyForm) {
          this.keyForm = {};
        }

        // 只设置开始和结束时间，不修改其他字段
        this.keyForm.startTime = currentDateTime;
        this.keyForm.endTime = endDateTime;
      },

      // 取消钥匙授权
      cancelKey() {
        this.showCustom = false;
        this.isShow = false;
        this.keyForm = {
          password: ""
        };
      },

      // 开始时间变更
      start() {
        // 如果没有设置结束时间，自动设置为开始时间后一个月
        if (!this.keyForm.endTime && this.keyForm.startTime) {
          const startDate = new Date(this.keyForm.startTime);
          const endDate = new Date(startDate);
          endDate.setMonth(startDate.getMonth() + 1);

          // 格式化日期
          const endYear = endDate.getFullYear();
          const endMonth = String(endDate.getMonth() + 1).padStart(2, '0');
          const endDay = String(endDate.getDate()).padStart(2, '0');
          const endHours = String(endDate.getHours()).padStart(2, '0');
          const endMinutes = String(endDate.getMinutes()).padStart(2, '0');
          const endSeconds = String(endDate.getSeconds()).padStart(2, '0');

          this.keyForm.endTime = `${endYear}-${endMonth}-${endDay} ${endHours}:${endMinutes}:${endSeconds}`;
        }

        // 原有逻辑：如果已选择时间周期，则再次计算结束时间
        if (this.radio != null) {
          this.handleRadioChange(this.radio);
        }
      },

      // 时间周期选择
      handleRadioChange(value) {
        const startDate = new Date(this.keyForm.startTime);
        let endDate = new Date(startDate);

        if (value.includes('周')) {
          const weeks = parseInt(value);
          endDate.setDate(startDate.getDate() + (weeks * 7));
        } else if (value.includes('月')) {
          const months = parseInt(value);
          endDate.setMonth(startDate.getMonth() + months);
        } else if (value.includes('年')) {
          const years = parseInt(value);
          endDate.setFullYear(startDate.getFullYear() + years);
        }

        this.keyForm.endTime = endDate;
      },

      // 提交钥匙授权
      submitFormRuzhu() {
        // 确保有结束时间
        if (!this.keyForm.endTime && this.keyForm.startTime) {
          const startDate = new Date(this.keyForm.startTime);
          const endDate = new Date(startDate);
          endDate.setMonth(startDate.getMonth() + 1);
          this.keyForm.endTime = formatDateTime(endDate);
        }

        // 调试输出 keyForm 的值
        console.log("表单提交前 keyForm 的值:", {
          relation: this.keyForm.relation,
          userName: this.keyForm.userName,
          userPhone: this.keyForm.userPhone,
          type: this.radioType,
          password: this.keyForm.password
        });

        this.$refs["keyForm"].validate(valid => {
          if (valid) {


            // 根据当前类型保存值到对应变量
            if (this.radioType === '1') {
              this.passwordValue = this.keyForm.password;
            } else {
              this.cardValue = this.keyForm.password;
            }
            // 准备提交的数据 - 确保使用正确的字段名称
            const submitData = {
              ...this.keyForm,
              type: this.radioType, // radioType的值已经是正确的类型码：'1'表示密码，'2'表示卡片
              endTime: formatDateTime(this.keyForm.endTime),
              userName: this.keyForm.userName,
              relationName: this.keyForm.userName,
              userPhone: this.keyForm.userPhone,
              cardNo: this.radioType === '2' ? this.keyForm.password : undefined // 只在卡片类型时传递cardNo
            };

            console.log("提交数据：", submitData); // 调试用，查看提交的数据

            // 统一使用批量添加接口，不管是单个还是多个房间
            let rooms = [];

            if (this.tenantInfo.isBatch && this.tenantInfo.selectedRooms && this.tenantInfo.selectedRooms.length > 1) {
              // 多个房间：使用选中的房间列表
              rooms = this.tenantInfo.selectedRooms.map(room => ({
                homeId: room.id,
                cellId: room.cellId,
                unitId: room.unitId,
                floorId: room.floorId
              }));
            } else {
              // 单个房间：构造单个房间数据
              rooms = [{
                homeId: this.tenantInfo.homeId || this.tenantInfo.roomInfo?.id,
                cellId: this.tenantInfo.cellId || this.tenantInfo.roomInfo?.cellId,
                unitId: this.tenantInfo.unitId || this.tenantInfo.roomInfo?.unitId,
                floorId: this.tenantInfo.floorId || this.tenantInfo.roomInfo?.floorId
              }];
            }

            // 准备批量数据，统一发送到后台
            const batchData = {
              baseInfo: submitData, // 基础信息
              rooms: rooms
            };

            // 先显示办理钥匙进度对话框
            this.showKeyAuthProgressDialog(this.tenantInfo);

            // 构建socketId：用户ID_业务名
            const socketId = `${this.tenantInfo.id || this.tenantInfo.userId}_key_auth`;
            
            // 先连接WebSocket，确保连接成功后再调用办理钥匙接口
            this.connectKeyAuthWebSocket(socketId, this.tenantInfo).then(() => {
              // WebSocket连接成功后，再调用办理钥匙接口
              this.handleBatchAddTenantkeyWithWebSocket(batchData, socketId);
            }).catch(error => {
              console.error('WebSocket连接失败:', error);
              this.$modal.msgError('WebSocket连接失败，请稍后重试');
              // 关闭进度对话框
              this.keyAuthProgressVisible = false;
            });
          }
        });
      },

      // 批量添加钥匙
      handleBatchAddTenantkey(batchData) {
        return batchAddTenantkey(batchData);
      },

      // 支持WebSocket推送的批量添加钥匙
      handleBatchAddTenantkeyWithWebSocket(batchData, socketId) {
        console.log('开始通过WebSocket推送方式办理钥匙:', {
          batchData: batchData,
          socketId: socketId
        });

        // 调用现有的批量添加接口，传递socketId参数
        // 后端会自动通过WebSocket推送进度
        batchAddTenantkey(batchData, { socketId: socketId }).then(response => {
          console.log('办理钥匙请求已发送:', response);
          // 关闭办理钥匙对话框
          this.isShow = false;
          this.showCustom = false;
        }).catch(error => {
          console.error('办理钥匙请求失败:', error);
          this.$modal.msgError('办理钥匙请求失败，请重试');
          // 关闭进度对话框
          this.keyAuthProgressVisible = false;
        });
      },

      // 显示批量添加结果
      showBatchResult(responseData) {
        const { successCount, failCount, successRooms, failedRooms } = responseData;

        let message = `<div style="text-align: left;">`;
        message += `<h4 style="margin-bottom: 15px; color: #67c23a;">批量添加结果</h4>`;

        // 成功统计
        message += `<div style="margin-bottom: 15px;">`;
        message += `<p style="color: #67c23a; font-weight: bold;">✅ 成功：${successCount} 个房间</p>`;
        if (successRooms && successRooms.length > 0) {
          message += `<div style="margin-left: 20px; color: #606266;">`;
          successRooms.forEach(room => {
            message += `<div>• 房间ID: ${room.homeId}</div>`;
          });
          message += `</div>`;
        }
        message += `</div>`;

        // 失败统计
        if (failCount > 0) {
          message += `<div style="margin-bottom: 15px;">`;
          message += `<p style="color: #f56c6c; font-weight: bold;">❌ 失败：${failCount} 个房间</p>`;
          if (failedRooms && failedRooms.length > 0) {
            message += `<div style="margin-left: 20px; color: #f56c6c; max-height: 300px; overflow-y: auto; padding-right: 10px;">`;
            failedRooms.forEach(room => {
              message += `<div style="margin-bottom: 5px;">• 房间ID: ${room.homeId} - ${room.message}</div>`;
            });
            message += `</div>`;
          }
          message += `</div>`;
        }

        message += `</div>`;

        this.$alert(message, '批量添加结果', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          customClass: 'batch-result-dialog',
          closeOnClickModal: false,
          closeOnPressEscape: false
        });
      },

      // 显示办理钥匙进度对话框
      showKeyAuthProgressDialog(userData) {
        // 设置用户信息
        this.keyAuthProgressData = {
          name: userData.name,
          idCardNumber: userData.idCardNumber
        };

        // 重置进度状态
        this.keyAuthProgress = {
          current: 0,
          total: 0,
          status: 'processing',
          message: '正在初始化办理钥匙流程...',
          details: []
        };

        // 显示对话框
        this.keyAuthProgressVisible = true;
      },

      // 连接办理钥匙结果WebSocket
      connectKeyAuthWebSocket(socketId, userData) {
        return new Promise((resolve, reject) => {
          try {
            // 关闭之前的连接
            if (this.keyAuthWebSocket) {
              this.keyAuthWebSocket.close();
            }

            // 构建WebSocket URL，从环境变量读取
            const wsBaseUrl = process.env.VUE_APP_WS_URL || 'ws://localhost:8082';
            const wsUrl = `${wsBaseUrl}/websocket/${socketId}`;
            console.log('办理钥匙WebSocket连接信息:', {
              socketId: socketId,
              wsBaseUrl: wsBaseUrl,
              wsUrl: wsUrl
            });

            this.keyAuthWebSocket = new WebSocket(wsUrl);

            // 设置连接超时
            const connectionTimeout = setTimeout(() => {
              reject(new Error('WebSocket连接超时'));
            }, 5000); // 5秒超时

            this.keyAuthWebSocket.onopen = (event) => {
              console.log('办理钥匙结果WebSocket连接成功:', socketId);
              clearTimeout(connectionTimeout);
              resolve(); // 连接成功，resolve Promise
            };

            this.keyAuthWebSocket.onmessage = (event) => {
              console.log('收到办理钥匙WebSocket消息:', {
                data: event.data,
                type: typeof event.data,
                timestamp: new Date().toISOString()
              });

              try {
                // 检查消息是否为JSON格式
                if (event.data && typeof event.data === 'string') {
                  // 尝试解析JSON
                  if (event.data.trim().startsWith('{') || event.data.trim().startsWith('[')) {
                    const data = JSON.parse(event.data);
                    console.log('解析JSON成功:', data);
                    this.handleKeyAuthResultMessage(data);
                  } else {
                    // 处理非JSON格式的消息（如"连接成功"）
                    console.log('收到非JSON格式消息:', event.data);
                    if (event.data === '连接成功') {
                      console.log('WebSocket连接已建立，等待办理钥匙结果...');
                    }
                  }
                }
              } catch (error) {
                console.error('解析WebSocket消息失败:', error);
              }
            };

            this.keyAuthWebSocket.onclose = (event) => {
              console.log('办理钥匙结果WebSocket连接关闭:', socketId);
            };

            this.keyAuthWebSocket.onerror = (error) => {
              console.error('办理钥匙结果WebSocket连接错误:', error);
              clearTimeout(connectionTimeout);
              this.keyAuthProgress.status = 'error';
              this.keyAuthProgress.message = 'WebSocket连接失败';
              reject(new Error('WebSocket连接失败')); // 连接失败，reject Promise
            };
          } catch (error) {
            console.error('创建WebSocket连接失败:', error);
            reject(error);
          }
        });
      },

      // 处理办理钥匙结果消息
      handleKeyAuthResultMessage(data) {
        console.log('收到办理钥匙结果消息:', data);

        switch (data.type) {
          case 'key_auth_progress':
            // 处理单个房间的办理钥匙进度
            this.keyAuthProgress.current = data.current;
            this.keyAuthProgress.total = data.total;
            this.keyAuthProgress.status = 'processing';
            this.keyAuthProgress.message = data.message;

            // 添加办理钥匙失败的房间到详情列表
            console.log('处理进度消息，检查是否有失败信息:', {
              hasData: !!data.data,
              dataMessage: data.data?.message,
              mainMessage: data.message,
              data: data.data
            });
            
            // 检查是否是失败消息（包含"失败"或"异常"关键词）
            const isFailure = (data.data && data.data.message && 
                              (data.data.message.includes('失败') || data.data.message.includes('异常'))) ||
                             (data.message && 
                              (data.message.includes('失败') || data.message.includes('异常')));
            
            console.log('判断是否为失败消息:', {
              dataMessage: data.data?.message,
              mainMessage: data.message,
              isFailure: isFailure
            });
            
            if (isFailure) {
              // 构建失败房间信息
              const roomResult = {
                roomName: data.data?.roomName || '未知房间',
                cellName: data.data?.cellName || '-',
                unitName: data.data?.unitName || '-',
                floorName: data.data?.floorName || '-',
                keyType: data.data?.keyType || '未知',
                errorReason: data.data?.message || data.message || '未知错误',
                status: 'error',
                time: new Date().toLocaleTimeString()
              };
              
              // 添加到详情列表
              this.keyAuthProgress.details.push(roomResult);
              console.log('添加失败房间到详情列表:', roomResult);
              console.log('当前详情列表长度:', this.keyAuthProgress.details.length);
              
              // 强制更新视图
              this.$forceUpdate();
            } else {
              console.log('不是失败消息，跳过失败信息处理');
            }
            break;

          case 'key_auth_complete':
            // 办理钥匙完成
            this.keyAuthProgress.status = 'success';
            this.keyAuthProgress.current = data.total;
            this.keyAuthProgress.message = data.message;

            // 显示详细结果
            if (data.data) {
              this.showKeyAuthResultDetails(data.data);
            }

            // 关闭WebSocket连接
            if (this.keyAuthWebSocket) {
              this.keyAuthWebSocket.close();
              this.keyAuthWebSocket = null;
            }

            // 刷新列表
            this.$emit('refresh');
            break;

          case 'key_auth_error':
            // 办理钥匙出错
            this.keyAuthProgress.status = 'error';
            this.keyAuthProgress.message = data.message;

            // 关闭WebSocket连接
            if (this.keyAuthWebSocket) {
              this.keyAuthWebSocket.close();
              this.keyAuthWebSocket = null;
            }
            break;

          default:
            console.log('未知消息类型:', data.type);
        }
      },

      // 显示办理钥匙结果详情
      showKeyAuthResultDetails(data) {
        // 这里可以显示详细的办理钥匙结果，比如成功和失败的房间列表
        console.log('办理钥匙结果详情:', data);
      },

      // 获取办理钥匙进度状态类型
      getKeyAuthProgressStatusType() {
        switch (this.keyAuthProgress.status) {
          case 'success':
            return 'success';
          case 'error':
            return 'danger';
          default:
            return 'warning';
        }
      },

      // 获取办理钥匙进度状态文本
      getKeyAuthProgressStatusText() {
        switch (this.keyAuthProgress.status) {
          case 'success':
            return '完成';
          case 'error':
            return '错误';
          default:
            return '处理中';
        }
      },

      // 获取详细状态类型
      getDetailStatusType(status) {
        switch (status) {
          case 'success':
            return 'success';
          case 'error':
            return 'danger';
          case 'processing':
            return 'warning';
          default:
            return 'info';
        }
      },

      // 获取详细状态文本
      getDetailStatusText(status) {
        switch (status) {
          case 'success':
            return '成功';
          case 'error':
            return '失败';
          case 'processing':
            return '处理中';
          default:
            return '未知';
        }
      },

      // 一键复制所有失败信息
      copyAllFailureInfo() {
        if (this.keyAuthProgress.details.length === 0) {
          this.$message.warning('没有失败信息可复制');
          return;
        }

        // 构建复制内容
        let copyText = `办理钥匙失败信息汇总\n`;
        copyText += `时间: ${new Date().toLocaleString()}\n`;
        copyText += `用户: ${this.keyAuthProgressData.name || '未知'}\n`;
        copyText += `学工号: ${this.keyAuthProgressData.idCardNumber || '未知'}\n`;
        copyText += `总房间数: ${this.keyAuthProgress.total}\n`;
        copyText += `失败房间数: ${this.keyAuthProgress.details.length}\n\n`;
        copyText += `失败详情:\n`;
        copyText += `序号\t校区\t楼栋\t楼层\t房间\t钥匙类型\t失败原因\t时间\n`;
        copyText += `─\t─\t─\t─\t─\t─\t─\t─\n`;

        this.keyAuthProgress.details.forEach((detail, index) => {
          copyText += `${index + 1}\t${detail.cellName}\t${detail.unitName}\t${detail.floorName}\t${detail.roomName}\t${detail.keyType}\t${detail.errorReason}\t${detail.time}\n`;
        });

        // 复制到剪贴板
        this.copyToClipboard(copyText);
      },

      // 复制文本到剪贴板
      copyToClipboard(text) {
        if (navigator.clipboard && window.isSecureContext) {
          // 使用现代 Clipboard API
          navigator.clipboard.writeText(text).then(() => {
            this.$message.success('失败信息已复制到剪贴板');
          }).catch(err => {
            console.error('复制失败:', err);
            this.fallbackCopyToClipboard(text);
          });
        } else {
          // 降级方案
          this.fallbackCopyToClipboard(text);
        }
      },

      // 降级复制方案
      fallbackCopyToClipboard(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
          const successful = document.execCommand('copy');
          if (successful) {
            this.$message.success('失败信息已复制到剪贴板');
          } else {
            this.$message.error('复制失败，请手动复制');
            console.log('复制内容:', text);
          }
        } catch (err) {
          console.error('复制失败:', err);
          this.$message.error('复制失败，请手动复制');
          console.log('复制内容:', text);
        }

        document.body.removeChild(textArea);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }

  .input-hint {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    line-height: 1.2;
  }

  // 批量结果对话框样式
  :global(.batch-result-dialog) {
    .el-message-box__content {
      max-height: 500px;
      overflow-y: auto;
    }

    .el-message-box__message {
      line-height: 1.6;
    }

    // 确保对话框内容可以滚动
    .el-message-box__wrapper {
      max-height: 80vh;
    }

    // 美化滚动条样式
    .el-message-box__content::-webkit-scrollbar {
      width: 8px;
    }

    .el-message-box__content::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    .el-message-box__content::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;
    }

    .el-message-box__content::-webkit-scrollbar-thumb:hover {
      background: #a8a8a8;
    }
  }

  // 办理钥匙进度对话框样式
  .key-auth-progress-content {
    .user-info {
      margin-bottom: 20px;
    }

    .progress-section {
      margin-bottom: 20px;

      .progress-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .progress-title {
          font-weight: 500;
          color: #303133;
        }

        .progress-text {
          color: #909399;
          font-size: 14px;
        }
      }

      .progress-status {
        margin-top: 10px;
        text-align: center;
      }
    }

    .status-message {
      margin-bottom: 20px;
      padding: 10px 15px;
      background-color: #f0f9ff;
      border-radius: 4px;
      border-left: 4px solid #409eff;
      display: flex;
        align-items: center;

      i {
        margin-right: 8px;
        color: #409eff;
      }

      span {
        color: #303133;
        font-size: 14px;
      }
    }

    .progress-details {
      .details-header {
        margin-bottom: 15px;
        font-weight: 500;
        color: #303133;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .el-table {
        .el-table__header {
          background-color: #f5f7fa;
        }
      }
    }
  }
</style>
